package high_scores;

import interfaces.IPlayer;

import java.util.ArrayList;
import java.util.List;

public class HighScores {

	private List<IPlayer> topFifteenPlayers;
	
	public HighScores() {
		topFifteenPlayers = new ArrayList<IPlayer>();
	}
	
	public void putUnsorted(IPlayer player) {
		topFifteenPlayers.add(player);
	}

	public void putSorted(IPlayer player) {
		// use modifyed binary search
		if (size() == 0) {
			topFifteenPlayers.add(player);
		} else {
			int currentPos = findPlayerPositionBinarySearch(player);
			
			if(player.compare(topFifteenPlayers.get(currentPos)) != -1)
				topFifteenPlayers.add(currentPos + 1, player);
			else 
				topFifteenPlayers.add(currentPos, player);
		}

		// remove the 16th player
		if (size() >= 16)
			topFifteenPlayers.remove(15);
	}

	private int findPlayerPositionBinarySearch(IPlayer player) {
		int startPos = 0;
		int endPos = size() - 1;
		int currentPos = (startPos + endPos) / 2;

		while (startPos != endPos) {
			if (player.compare(topFifteenPlayers.get(currentPos)) != -1 && currentPos + 1 < size()
					&& player.compare(topFifteenPlayers.get(currentPos + 1)) == -1)
				break;
			
			//change current position
			if(player.compare(topFifteenPlayers.get(currentPos)) == 1) 
				startPos = currentPos + 1;
			else 
				endPos = currentPos - 1;
			
			if(startPos > endPos)
				break;
			
			currentPos = (startPos + endPos) / 2;
		}
		
		return currentPos;
	}

	public int size() {
		return topFifteenPlayers.size();
	}

	public IPlayer getPlayer(int position) {
		IPlayer player = new Player((Player) topFifteenPlayers.get(position));
		return player;
	}
}
